<template>
  <div class="resmanage">
    <!--列表操作-->
    <basic-container v-if="showList">
      <avue-crud
        ref="crud"
        :table-loading="tableLoading"
        :data="tableData"
        :option="option"
        :page="page"
        :before-close="beforeClose"
        v-model="catalogForm"
        @on-load="getCatalogsData"
        @refresh-change="getCatalogsData"
        @row-save="rowSave"
        @row-del="rowDel"
        @row-update="(row , index , done) => rowSave(row , done)"
      >
        <template slot-scope="scope" slot="dirTypeForm">
          <div class="dirtype-select">
            <el-select v-model="catalogForm.dirType" @change="dirTypeChange" placeholder="请选择">
              <el-option :key="item.dictKey" v-for="item of dirTypes" :label="item.dictValue" :value="item.dictKey"></el-option>
            </el-select>
            <template v-if="selectStaticType">
              <el-select v-model="catalogForm.staticDirType" placeholder="请选择">
                <el-option
                  v-for="item in staticDirTypes"
                  :key="item.dictKey"
                  :label="item.dictValue"
                  :value="item.dictKey">
                </el-option>
              </el-select>
            </template>

          </div>
        </template>
        <template slot-scope="scope" slot="relationForm">
          <div class="relation-select">
            <el-select v-model="catalogForm.dataSourceType" @change="dataSourceTypeChange" placeholder="请选择">
              <el-option :key="item.value" v-for="item of dataSourceTypes" :label="item.label" :value="item.value"></el-option>
            </el-select>
            <el-select v-model="catalogForm.dataSourceDb" @change="dataSourceDbChange" placeholder="请选择">
              <el-option
                v-for="item in dataSources"
                :key="item.name"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select>
            <el-select v-model="catalogForm.dataSourceTable" @change="dataSourceTableChange"  placeholder="请选择">
              <el-option
                v-for="item in tables"
                :key="item.name"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select>
          </div>
          <div class="clear-f"></div>
          <el-table
            stripe
            border
            :data="tableData1"
            style="width: 100%;margin-top: 10px;max-height: 200px;">
            <el-table-column
              prop="columnName"
              label="字段">
            </el-table-column>
            <el-table-column
              prop="columnType"
              label="数据类型">
            </el-table-column>
            <el-table-column
              prop="columnComment"
              label="描述">
            </el-table-column>
          </el-table>
        </template>
        <template slot-scope="scope" slot="labelListForm">
          <el-tag
            size="mini"
            v-for="(tag,index) in tags"
            :key="tag"
            closable
            @close="deleteTag(tag,index)"
            :type="tag">
            {{labels[tag]}}
          </el-tag>
          <i class="el-icon-edit operation mar-l-10" @click="addTag"></i>
        </template>
        <template slot-scope="{row , size , type , index}" slot="menu">
          <el-button icon="el-icon-edit" :size="size" :type="type" @click="openRowEdit(row , index)">编辑</el-button>
        </template>
      </avue-crud>
    </basic-container>
    <el-dialog custom-class="dialog-width" append-to-body title="添加标签" :visible.sync="tagFormVisible">
      <el-form>
        <el-form-item label="选择标签" :label-width="formLabelWidth">
          <el-cascader
            class="dis-b"
            :options="options"
            v-model="tags"
            :props="{'multiple': true , label: 'name', value: 'id' , emitPath: false, checkStrictly: true}"
            @change="consoleLog(tags)"
            :show-all-levels="false"
            clearable></el-cascader>
          <!-- <el-select class="dis-b" multiple v-model="tags" filterable placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item">
            </el-option>
          </el-select> -->
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="tagCancel">取 消</el-button>
        <el-button type="primary" @click="confirmAddTag">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { mapActions } from 'vuex'
  import { getCatalogs , saveCatalog, deleteCatalog, getDictDirTypes, getDictStaticDirTypes } from '@/api/resourceCatalog/resmanage'
  import datasourceTypeList from '@/config/datasourceTypeList'
  import { apiUrls } from '@/api/resourceCatalog/classification';
  import labelApi from '@/api/label';

  export default {
    data() {
      return {
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        tableLoading: false,
        tagForm:{
          tag:''
        },
        tagFormVisible:false,
        showList:true,
        formLabelWidth: '100px',
        options: [],
        labels: {},
        tags: [],
        tableData1: [],
        tableData: [],
        option : {
          editBtn: false,
          column:[
            {
              label:'名称',
              prop:'name',
              rules: [{
                required: true,
                message: "请输入名称",
                trigger: "blur"
              }]
            },
            {
              label:'主题',
              prop:'topicId',
              props: {
                label: "name",
                value: "id"
              },
              type: "select",
              dataType: "string",
              dicUrl: apiUrls.theme.list,
              rules: [{
                required: true,
                message: "请选择主题",
                trigger: "blur"
              }]
            },
            {
              label:'行业',
              prop:'industryId',
              props: {
                label: "name",
                value: "id"
              },
              type: "select",
              dataType: "string",
              dicUrl: apiUrls.industry.list,
              rules: [{
                required: true,
                message: "请选择行业",
                trigger: "blur"
              }]
            },
            {
              label:'共享类型',
              prop:'shareTypeId',
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              type:'select',
              dicUrl: '/api/blade-system/dict-biz/dictionary?code=SHARE_TYPE'
            },
            {
              label:'更新频率',
              prop:'updateFrequencyDictId',
              type:'select',
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dicUrl: '/api/blade-system/dict-biz/dictionary?code=UPDATE_FREQUENCY',
            },
            {
              label:'创建人',
              prop:'createUserName',
              display:false
            },
            {
              label: "创建时间",
              prop: "createTime",
              type: "date",
              format: "yyyy-MM-dd hh:mm:ss",
              valueFormat: "yyyy-MM-dd hh:mm:ss",
              display:false
            },
            {
              label: "标签",
              prop: "labelList",
              hide: true,
              dicUrl: labelApi.apiUrls.tree
            },
            {
              label: "目录类型",
              prop: "dirType",
              hide: true
            },
            {
              label: "描述",
              prop: "description",
              type: "textarea",
              minRows: 2,
              span: 24,
              hide: true
            },
            {
              label: "关联数据集",
              prop: "relation",
              span: 24,
              hide: true
            }
          ]
        },
        currentPage4: 1,
        catalogForm: {
          name: '',
          theme:'',
          industry:'',
          shareType:'',
          frequency:'',
          dataSourceType:'',
          dataSourceDb:'',
          dataSourceTable:'',
          dirType:'static',
          staticDirType:''
        },
        rules: {
          name: [
            {required: true, message: '请输入名称', trigger: 'blur'}
          ]
        },
        dataSourceTypes: datasourceTypeList,
        dirTypes: [
        ],
        staticDirTypes: [
        ],
        selectStaticType:true,
        dataSources:[],
        tables: [],
        thmems: [],
        industry: []
      }
    },
    mounted() {
      labelApi.treeLabel().then(
        res => {
          this.options = this.translateTreeData(res.data.children || [])
        }
      );
      this.getDirTypes();
      this.getStaticDirTypes();
    },
    methods:{
      ...mapActions('datasource', ['getDatasourcesList' , 'getTablesByDatasourceId' , 'queryDataSourceTableDesc']),
      getDirTypes() {
        getDictDirTypes().then( res => {
          this.dirTypes = res['data']['data'];
        });
      },
      getStaticDirTypes() {
        getDictStaticDirTypes().then( res => {
          this.staticDirTypes = res['data']['data'];
        });
      },
      dirTypeChange() {
        this.selectStaticType = this.catalogForm.dirType !== 'CATALOG_DYNAMIC';
      },
      confirmAddTag() {
        this.tagFormVisible = false;
        this.tagForm.tag = '';
      },
      translateTreeData(treeData){
        let newTreeData = [];
        treeData.forEach(
          item => {
            let el = {
              ...item.label
            }
            this.labels[el.id] = el.name;
            if(item.children && item.children.length){
              el['children'] = this.translateTreeData(item['children']);
            }
            newTreeData.push(el);
          }
        )
        return newTreeData;
      },
      openRowEdit(row , index){
        this.tags = [];
        labelApi.listLabelResourceRelation({
          resourceId: row.id
        }).then(
          res => {
            if(res.data.data.records){
              res.data.data.records.forEach(
                item => {
                  if(this.tags.indexOf(item['labelId']) < 0){
                    this.tags.push(''+item['labelId']);
                    if(!this.labels[item['labelId']]){
                      this.labels[item['labelId']] = item['labelName'];
                    }
                  }
                }
              )
            }
          }
        )
        this.$refs.crud.rowEdit(row , index)
      },
      consoleLog(d){
        console.log(d)
      },
      dataSourceTypeChange(){
        this.catalogForm.dataSourceDb = '';
        this.getDatasourcesList({
          type: this.catalogForm.dataSourceType
        }).then(
          res => {
            this.dataSources = res['data'];
          }
        )
      },
      dataSourceTableChange(){
        this.tableData1 = [];
        let id = '';
        this.dataSources.forEach(
          item => {
            if(item.name === this.catalogForm.dataSourceDb){
              id = item.id;
            }
          }
        )
        this.queryDataSourceTableDesc({
          id: id,
          tableName: this.catalogForm.dataSourceTable
        }).then(
          res => {
            this.tableData1 = res.data.tableDescList;
          }
        )
      },
      dataSourceDbChange(){
        this.catalogForm.dataSourceTable = '';
        let id = '';
        this.dataSources.forEach(
          item => {
            if(item.name === this.catalogForm.dataSourceDb){
              id = item.id;
            }
          }
        )
        this.getTablesByDatasourceId(id).then(
          res => {
            this.tables = (res.data.data || []).map(item => ({name: item}));
          }
        )
      },
      tagCancel() {
        this.tagFormVisible = false;
        this.tagForm.tag = '';
      },
      deleteTag(tag,index) {
        this.tags.splice(index,1)
      },
      addTag() {
        this.tagFormVisible = true;
      },
      getCatalogsData() {
        this.tableLoading = true;
        getCatalogs({
          current: this.page.currentPage,
          size: this.page.pageSize
        }).then( res => {
          this.tableLoading = false;
          res.data['data'].records.forEach(item => {
            item['shareTypeId'] = item['shareTypeId'] + '';
            item['updateFrequencyDictId'] = item['updateFrequencyDictId'] + '';
          });
          this.tableData = res.data['data'].records;
          this.page.total = res.data['data'].total;
        }).catch(() => {
          this.tableLoading = false;
        });
      },
      handleEdit() {

      },
      handleDelete() {

      },
      handleSizeChange() {
      },
      handleCurrentChange() {
      },
      addCatalog() {
        this.showList = false;
      },
      beforeClose(done) {
        this.tableData1 = [];
        done();
      },
      rowSave(row , done){
        row.labelList = this.tags;
        // this.tags = []
        saveCatalog(row).then(
          res => {
            done();
            this.getCatalogsData();
          }
        )
      },
      rowDel(row) {
        let _t = this;
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            deleteCatalog({
              ids:row['id']
            }).then(res => {
              _t.getCatalogsData();
            })
          })
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          this.showList = true;
          this.resetForm('catalogForm');
        });
      },
      cancelForm() {
        this.showList = true;
        this.resetForm('catalogForm');
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>
<style lang="scss">
  .dirtype-select {
    display: flex;
    justify-content: space-between;
    .el-select {
      width: 49% !important;
    }
  }
  .relation-select {
    display: flex;
    justify-content: space-between;
    .el-select {
      width: 33% !important;
    }
  }
  .resmanage {
    /*padding: 0 !important;*/
    .basic-container{
      padding-left: 0 !important;
      padding-right: 0 !important;
    }
  }
  .demo-catalogForm{
    input,textarea {
      width: 360px;
    }

  }
  .clear-f {
    clear: both;
  }
  .fr {
    float: right;
  }
  .h-40 {
    height: 50px;
  }
  .el-tag+.el-tag {
    margin-left: 10px;
  }
</style>
